<template>
  <!-- 表格操作页面 -->
  <div class="table-main">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="搜索内容：">
        <el-input
          v-model="searchdt.search"
          placeholder="请输入姓名"
          @input="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAdd()">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAdd()">添加</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="tableData"
      @selection-change="handleSelectionChange"
      style="width: 100%"
      stripe
    >
      <el-table-column :selectable="selectEnable" type="selection" width="55">
      </el-table-column>
      <el-table-column label="姓名" width="180" prop="name">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>姓名: {{ scope.row.name }}</p>
            <p>住址: {{ scope.row.address }}</p>
            <div slot="reference" class="name-wrapper">
              {{ scope.row.name }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="sex" label="性别"> </el-table-column>
      <el-table-column prop="tel" label="电话"> </el-table-column>
      <el-table-column prop="hobby" label="爱好"> </el-table-column>
      <el-table-column prop="address" label="地址"> </el-table-column>
      <el-table-column prop="createTime" label="创建时间"> </el-table-column>
      <!-- 操作按钮触发事件 -->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page.currentPage"
      :page-sizes="[100, 200, 300, 400]"
      :page-size="page.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total"
    >
    </el-pagination>
    <!-- 添加修改信息弹出框 -->
    <el-dialog
      :title="dialogType === 'edit' ? '编辑个人信息' : '添加个人信息'"
      :visible.sync="dialogVisible"
      width="30%"
      @close="close"
    >
      <el-form
        ref="userForm"
        :model="userForm"
        label-width="100px"
        style="width: 320px"
      >
        <el-form-item
          label="名字"
          prop="name"
          :rules="[
            {
              required: true,
              message: '名字不能为空',
              trigger: ['blur', 'change'],
            },
          ]"
        >
          <el-input v-model="userForm.name" placeholder="请输入名字" />
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="tel"
          :rules="[
            {
              pattern:
                /^^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
              message: '请输入合法手机号',
              trigger: ['blur', 'change'],
            },
          ]"
        >
          <el-input v-model="userForm.tel" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userForm.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="爱好" prop="hobby">
          <el-input v-model="userForm.hobby" placeholder="请输入爱好" />
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          :rules="[
            {
              message: '密码不能为空',
              trigger: ['blur', 'change'],
            },
          ]"
        >
          <el-input v-model="userForm.password" placeholder="请输入密码" />
        </el-form-item>

        <el-form-item label="家庭住址：" prop="address">
          <!-- <el-cascader
            v-model="userForm.address"
            :options="opctionList"
            @change="getarea"
            @expand-change="getarea"
            class="w300"
          /> -->
          <el-input v-model="userForm.address" placeholder="请输入密码" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// 引入工具库
import { debounce } from "lodash";
import axios from "axios";
export default {
  data() {
    return {
      searchdt: {
        search: "",
      },
      // 表格数据
      tableData: [],
      // 合并对象
      userForm: {
        name: "",
        address: "",
        hobby: "",
        name: "",
        password: "",
        sex: "",
        tel: "",
      },
      dialogVisible: false,
      dialogType: "",
      page: {
        pageSize: 1,
        currentPage: 5,
        total: 0,
      },
      //地址级联数据
      opctionList: [],
      multipleSelection: [],
    };
  },
  created() {
    this.getListUser();
    // this.opctionList = this.getareaList(this.areaList);
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    selectEnable(row, rowIndex) {
      if (row.sex == "男") {
        return false;
      } else {
        return true; // 不禁用
      }
    },
    headerStyle() {},

    getListUser() {
      axios({
        method: "post",
        url: " http://localhost:9999/user/listUser",
        data: {
          address: "",
          beginTime: "",
          endTime: "",
          name: "",
          page: this.page.currentPage,
          pageSize: this.page.pageSize,
        },
      })
        .then((result) => {
          const { records, total } = result.data.data;
          this.tableData = records;
          this.page.total = records.length;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    // 编辑按钮
    handleEdit({ id }) {
      this.dialogType = "edit";
      this.dialogVisible = true;
      // 定义弹框的标题
      axios({
        method: "get",
        url: "http://localhost:9999/user/userDetail",
        params: {
          id: id,
        },
      })
        .then((result) => {
          const { data } = result.data;
          if (result.status === 200) {
            this.userForm = { ...data };
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 点击删除   { $index, row }  解构scope
    handleDelete({ id }) {
      // 二次确认删除
      this.$confirm("Confirm to remove the role?", "Warning", {
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",
        type: "warning",
      })
        // 同步数据处理
        .then(() => {
          console.log(id, "id");
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleAdd() {
      // 定义弹框的标题
      this.dialogType = "add";
      this.dialogVisible = true;
    },
    // 搜索     防抖处理
    handleSearch: debounce(function () {}, 1000),
    handleSubmit() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          axios({
            method: "post",
            url: "http://localhost:9999/user/saveUser",
            data: { ...this.userForm },
          })
            .then((result) => {
              if (result.status === 200) {
                this.dialogVisible = false;
                this.$notify({
                  title: "Success",
                  dangerouslyUseHTMLString: true,
                  message: result.data.message,
                  type: "success",
                });
                this.getListUser();
              }
            })
            .catch((error) => {
              console.log(error);
            });
        } else {
          return false;
        }
      });

      // 判断是否编辑状态

      // ES6解构数据  输出信息提示添加成功
      // const { name, date, address } = this.form;
    },
    close() {
      this.$refs.userForm.resetFields();
    },
    // 优化Dom
    getarea(v) {
      this.opctionList = this.getareaList(v);
    },
    //  地址DOM优化   优化数据结构
    getareaList(area, series = 4) {
      let opctionList = [];
      // 获得到省份的数据
      for (const provincial in this.$pcaa["86"]) {
        opctionList.push({
          value: provincial,
          label: this.$pcaa["86"][provincial],
          children: [],
        });
      }
      let areaArr = opctionList; //利用内存引用
      area.forEach((item, index) => {
        if (series - 1 !== index) {
          let result = [];

          //遍历地址数据对象
          for (const code in this.$pcaa[item]) {
            //格式化子级
            let res = { value: code, label: this.$pcaa[item][code] };

            //当有子级时
            series - 2 !== index &&
              this.$pcaa[code] !== undefined &&
              (res.children = []);
            //给子集
            result.push(res);
          }
          if (!result.length) return;

          //找到子集
          for (const v of areaArr) {
            //如果CODE相等
            if (v.value === item) {
              //赋值给children
              v.children = result;
              areaArr = result;
              return;
            }
          }
        }
      });
      return opctionList;
    },
  },
  computed: {},
  watch: {},
};
</script>
<style scoped>
.table-main {
  padding: 50px;
}
.table-page {
  height: 5000px;
}
</style>
